import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getMAC } from '@/utils/getMAC';
const instance = axios.create({
  baseURL: 'http://api.qubit-dance.com:9000/qlback',
  withCredentials: false,
})

// 请求拦截器
instance.interceptors.request.use(
  async config => {
    const macAddress = await getMAC();
    config = {
      neddLogin: true,
      ...config,
    }

    const userStore = useUserStore()
    
    if (config.neddLogin) {
      if (userStore.checkLogin()) {
        config.headers['Authorization'] = `TOKEN ` + `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzExMzIwNjcsImlhdCI6MTczMTA0NTY2NywiZGF0YSI6eyJ1c2VybmFtZSI6ImZ0X2NodWFuMDAxIn19.eZEg_KAugu_zJCno4tcVB3lc8OlUgBeWAmZpHvQpoa8`
      }
    }
    config.headers['PLANTCODE'] = 'yanghao-plant'
    config.headers['MAC'] = macAddress

    return config
  },
  error => {
    ElMessage.error('请求超时')
    Promise.reject(error)
  }
)

// 相应拦截器
instance.interceptors.response.use(
  response => {
    const { data, status } = response

    if (status && status == 200) {
      // if ([403].includes(data.code)) {
      //   ElMessage.warning(data.msg || '账号已过期，请重新登录')
      //   const userStore = useUserStore()
      //   userStore.logout()
      //   return Promise.reject(data)
      // } 
      if ([401].includes(data.code)) {
        ElMessage.warning(data.data.msg || '账号已过期，请重新登录')
        const userStore = useUserStore()
        userStore.logout()
        // return Promise.reject(data)
      } else if (data.code != 200) {
        ElMessage.error(data.msg)
        return Promise.reject(data)
      }

      return data
    } else {
      
      ElMessage.error('接口错误')
      return Promise.reject(data)
    }
  },
  error => {
    if (error?.response?.status == 401 || error?.response?.status == 400) {
      ElMessage.warning(error?.response?.data?.msg || '账号已过期，请重新登录')
      const userStore = useUserStore()
      userStore.logout()
      return
    } else if (error?.response?.status == undefined) {
      // ElMessage.error('请求超时')
      const userStore = useUserStore()
      userStore.openerrordialog()
    } else {
      ElMessage.error('请求超时')
      // const userStore = useUserStore()
      // userStore.openerrordialog()
    }

    
    return Promise.reject(error)
  }
)

export const http = instance
export default instance
